package com.demo.demo.images;

import com.google.common.base.Stopwatch;
import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.TimeUnit;

/**
 *  最终合成标签
 *
 * @Author WuHuang
 * @Date 2023/5/11
 */
public class ImageMerger {
    //最终代码
    public static void main(String[] args) throws Exception {
        Stopwatch stopwatch = Stopwatch.createStarted();
        try {
            // 加载第一张图片
            File file1 = new File("D:\\WorkSpace\\wu\\spring-boot-study\\springboot-demo\\src\\main\\resources\\qiwei\\leee.png");
            BufferedImage image1 = ImageIO.read(file1);
            // 加载第二张图片
            URL url = new URL("https://images.lululemon.com/is/image/lululemon/LU9AX9S_058129_1");
            BufferedImage image2 = ImageIO.read(url);
            Graphics2D g = image1.createGraphics();

            mergerLabel(g,image1);

            mergerImages(g,image2);

            // 创建新的 BufferedImage，指定宽度和高度
            BufferedImage combined = new BufferedImage(image2.getWidth(), image2.getHeight(), BufferedImage.TYPE_INT_ARGB);
            // 获取 Graphics2D 对象
            g = (Graphics2D) combined.getGraphics();
            // 在背景色上绘制第二张图片
            g.drawImage(image2, 0, 0, null);
            // 在右上角绘制第一张图片
            int x = image2.getWidth() - image1.getWidth();
            int y = 0;
            g.drawImage(image1, x, y, null);

            // 压缩比例，0-1之间，数字越小压缩越多
            float compressionQuality = 0.2f;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(combined, "jpg", outputStream);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            File outputFile = new File("D:\\WorkSpace\\wu\\spring-boot-study\\springboot-demo\\src\\main\\resources\\qiwei\\output7.jpg");
//            Thumbnails.of(inputStream).
//                    scale(1)
//                    .outputQuality(0.2)
//                    .toFile(outputFile)
//                    ;
//             combined = compressImage(combined, compressionQuality);
            // 保存结果

            ImageIO.write((RenderedImage) outputStream, "png", outputFile);
            g.dispose();
            System.out.println("合成成功:" + stopwatch.elapsed(TimeUnit.SECONDS));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static BufferedImage scaleImage(BufferedImage inputImage, float quality, String format) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageWriter imgWriter = ImageIO.getImageWritersByFormatName(format).next();
        ImageWriteParam imgWriteParams = new JPEGImageWriteParam(null);
        // 要使用压缩，必须指定压缩方式为MODE_EXPLICIT
        imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
        // 这里指定压缩的程度，参数quality是取值0~1范围内，
        imgWriteParams.setCompressionQuality(quality);
        imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
        ColorModel colorModel = inputImage.getColorModel();
        imgWriteParams.setDestinationType(new ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(32, 32)));
        imgWriter.reset();
        // OutputStream构造
        imgWriter.setOutput(ImageIO.createImageOutputStream(out));
        imgWriter.write(null, new IIOImage(inputImage, null, null), imgWriteParams);
        InputStream inputStream = new ByteArrayInputStream(out.toByteArray());
        return ImageIO.read(inputStream);
    }

    public static BufferedImage compressImage(BufferedImage inputImage, float compressionQuality) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ByteArrayInputStream inputStream = null;
        ImageWriter writer = null;
        try {
            // 找到 JPEG 图像编码器
//            writer = ImageIO.getImageWritersByFormatName("png").next();
//            JPEGImageWriteParam param = new JPEGImageWriteParam(null);
            writer = ImageIO.getImageWritersByMIMEType("image/png").next();
            ImageWriteParam param = writer.getDefaultWriteParam();
            // 设置压缩质量参数
            if (param.canWriteCompressed()) {
                param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                param.setCompressionQuality(compressionQuality);
            }

            // 将图像写入输出流中
            writer.setOutput(ImageIO.createImageOutputStream(outputStream));
            writer.write(null, new IIOImage(inputImage, null, null), param);
            // 使用字节数组流创建输入流
            inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            // 从输入流中读取图片数据并返回 BufferedImage
            BufferedImage outputImage = ImageIO.read(inputStream);
            return outputImage;
        } finally {
            // 关闭流资源，注意需要判空
            if (outputStream != null) {
                outputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (writer != null) {
                writer.dispose();
            }
        }
    }


    private static void mergerLabel(Graphics2D g,BufferedImage resizedImage){
        // 获取 Graphics2D 对象
        g = (Graphics2D) resizedImage.getGraphics();
        Font font = new Font("PingFang SC", Font.BOLD, 62);
        // 第一个价格标签
        String price1 = "活动价: ¥1380.00";
        int x1 = 44;
        int y1 = 65;
        addPriceTag(g, price1, x1, y1, font, Color.WHITE, false);
        // 第二个价格标签
        Font font2 = new Font("PingFang SC", Font.BOLD, 58);
        String price2 = "吊牌价: ¥1080.00";
        int x2 = 77;
        int y2 = 250;
        addPriceTag(g, price2, x2, y2, font2, Color.BLACK, true);
    }

    private static void mergerImages(Graphics2D g,BufferedImage image2){
        // 获取新图像的图形对象
        g = image2.createGraphics();
        // 将原始图像绘制到新图像上
        g.drawImage(image2, 0, 0, null);
        // 在新图像的中心填充一个半透明的黑色矩形
        int labelWidth = 1800;
        int labelHeight = 320;
        int labelX = (image2.getWidth() - labelWidth) / 2;
        int labelY = (image2.getHeight() - labelHeight);
        g.setColor(new Color(0, 0, 0, 128));
        g.fillRect(0, labelY, labelWidth, labelHeight);

        // Add the label text to the new image
        g.setColor(Color.WHITE);
        g.setFont(new Font("PingFang SC", Font.BOLD, 106));
        String labelText = "Align HR Crop 23 Inch High Waist";
        int stringWidth = g.getFontMetrics().stringWidth(labelText);
        int x = labelX + (labelWidth - stringWidth) / 2;
        int y = labelY + ((labelHeight - g.getFontMetrics().getHeight()) / 2) + g.getFontMetrics().getAscent();
        g.drawString(labelText, x, y);
    }


    /**
     * 添加一个价格标签到图像上的指定位置。
     *
     * @param g2d 绘制上下文
     * @param price 价格
     * @param x 标签左上角的x坐标
     * @param y 标签左上角的y坐标
     * @param font 字体
     * @param textColor 文字颜色
     * @param drawLine 是否绘制删除线
     */
    private static void addPriceTag(Graphics2D g2d, String price, int x, int y,
                                    Font font, Color textColor, boolean drawLine) {
        // 获取字体度量值
        FontMetrics fm = g2d.getFontMetrics(font);
        int textWidth = fm.stringWidth(price);
        int labelHeight = fm.getHeight();
        // 绘制文字
        g2d.setFont(font);
        g2d.setColor(textColor);
//        g2d.drawString(price, x + 5, y - 3);
        g2d.drawString(price, x, y + labelHeight);
        // 绘制删除线
        if (drawLine) {
            g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
//            g2d.drawLine(x + 90, y - 10, x + textWidth + 5, y - 10);
            g2d.drawLine(x + 200, y + 58 , x + textWidth + 5, y + 58);

        }
    }

    //public static void main(String[] args) throws Exception {
//    try {
//        // 加载第一张图片
//        File file1 = new File("D:\\WorkSpace\\wu\\spring-boot-study\\springboot-demo\\src\\main\\resources\\scene2.png");
//        BufferedImage image1 = ImageIO.read(file1);
//
//        // 获取 Graphics2D 对象
//        Graphics2D g = (Graphics2D) image1.getGraphics();
//        Font font = new Font("宋体", Font.BOLD, 130);
//
//        // 第一个价格标签
//        String price1 = "活动价:¥102.99";
//        int x1 = 100;
//        int y1 = 270;
//        addPriceTag(g, price1, x1, y1, font, Color.WHITE, false);
//
//        // 第二个价格标签
//        Font font2 = new Font("宋体", Font.BOLD, 110);
//        String price2 = "吊牌价:¥122.99";
//        int x2 = x1 + 100;
//        int y2 = y1 + 360;
//        addPriceTag(g, price2, x2, y2, font2, Color.BLACK, true);
//
//        // 缩放第一张图片到指定尺寸
//        int desiredWidth = 220;
//        int desiredHeight = 135;
//        BufferedImage resizedImage1 = new BufferedImage(desiredWidth, desiredHeight, image1.getType());
//        g = resizedImage1.createGraphics();
//        g.drawImage(image1, 0, 0, desiredWidth, desiredHeight, null);
//        g.dispose();
//
//        // 加载第二张图片
//        URL url = new URL("https://pic.616pic.com/photoone/00/07/29/619762ba2cace5236.jpg");
//        BufferedImage image2 = ImageIO.read(url);
//
//        // 创建新的BufferedImage，指定宽度和高度
//        int width = image2.getWidth();
//        int height = image2.getHeight();
//        BufferedImage combined = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
//
//        // 获取Graphics2D对象
//        g = (Graphics2D) combined.getGraphics();
//
//        // 在背景色上绘制第二张图片
//        g.drawImage(image2, 0, 0, null);
//
//        // 在右上角绘制缩小后的第一张图片
//        int x = image2.getWidth() - resizedImage1.getWidth();
//        int y = 0;
//        g.drawImage(resizedImage1, x, y, null);
//
//        // 保存结果
//        File outputFile = new File("D:\\WorkSpace\\wu\\spring-boot-study\\springboot-demo\\src\\main\\resources\\output.png");
//        ImageIO.write(combined, "png", outputFile);
//
//        g.dispose();
//
//    } catch (IOException e) {
//        e.printStackTrace();
//    }
//}

}

